package com.qf.blogsystem.core.utils;

import com.qf.blogsystem.dto.EmailDto;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * @author Crazy
 * @version 1.0
 * @description: 发送邮件工具类
 * @date 2022/12/6 0:15
 */
public class EmailUtils {
    /**
     *
     * @param emailDto
     * @throws Exception
     */
    public static void sendEmailInfoUser(EmailDto emailDto) throws Exception {
        //创建配置文件对象
        Properties properties = new Properties();
        //设置服务器名称
        properties.setProperty("mail.host", "smtp.163.com");
        //设置邮件传输协议
        properties.setProperty("mail.transport.protocol", "smtp");
        //设置是否要验证服务器用户名和密码
        properties.setProperty("mail.smtp.auth", "true");

        //创建客户端与邮箱服务器的Session对象
        Session session = Session.getInstance(properties);
        //开启session的debug模式,方便查看发送email的运行状态
        session.setDebug(true);
        //通过session得到transport传输对象
        Transport transport = session.getTransport();
        //使用用户名密码连接上邮箱服务器,此处的密码需要到邮箱开启服务设置
        transport.connect("smtp.163.com", "krx508166115@163.com", "NPTEHMVIYWISPLWC");
        //创建邮件
        Message message = createSimpleMail(session, emailDto);
        //发送邮件
        transport.sendMessage(message, message.getAllRecipients());
        //关闭传输对象
        transport.close();
    }

    /**
     * 设置发送邮件的内容
     * @param session
     * @param emailDto
     * @return Message
     * @throws Exception
     */
    private static Message createSimpleMail(Session session, EmailDto emailDto) throws Exception {
        // 创建邮件对象
        MimeMessage message = new MimeMessage(session);
        // 指明邮件的发件人
        message.setFrom(new InternetAddress("krx508166115@163.com"));
        // 指明邮件的收件人
        message.setRecipient(Message.RecipientType.TO, new InternetAddress(emailDto.getToUser()));
        // 邮件的标题
        message.setSubject(emailDto.getTilte());
        // 邮件的内容
        message.setContent(emailDto.getContent(), "text/html;charset=UTF-8");
        // 设置抄送人
        message.setRecipients(Message.RecipientType.CC, InternetAddress.parse("krx508166115@163.com"));

        return message;
    }
}
